package com.oe.monitor;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;

public class TP99Calculator {

    private static Logger logger = LoggerFactory.getLogger(TP99Calculator.class);



    final static  long DEFAULT_MAX_TIME=6000;

    /**
     * max time
     */
    private long  maxTime=DEFAULT_MAX_TIME;

    /**
     * key记录
     */
    private TreeMap<Long, Long> treeMap ;


    private final double tp=0.99;


    public TP99Calculator() {
        treeMap= new TreeMap<>(Comparator.naturalOrder());
    }

    public  synchronized  void recordTime(long t){
       // logger.warn("========"+Thread.currentThread().getName()+"===========收集到信息:"+t+"=============");
        //不能超过最大时间，到达一定时间应该告警
        if(t>maxTime){
            t=maxTime;
        }
        Long count = treeMap.get(t);
        if(count==null){
            treeMap.put(t,1L);
        }else {
            treeMap.put(t,count+1);
        }
    }



    public double calculateTP99(){
        TreeMap<Long, Long> transMap = new TreeMap<>(Comparator.naturalOrder());
        AtomicReference<Long> idx= new AtomicReference<>(0l);
        treeMap.forEach((key,value)->{
            transMap.put(idx.get(),key);
            idx.updateAndGet(v -> v + value);
        });
        Long total=treeMap.values().stream().mapToLong(o->o).sum();

        Double idx99= Math.ceil((double)total*tp/100);

        Map.Entry<Long, Long> idx99Entry = transMap.floorEntry(idx99.longValue());
        Long TP99=idx99Entry.getValue();
        return  TP99;
    }

}
